<template>
  <div class="supperbox">
    <div class="lefttree">
      <el-input
      size="small"
      style="margin-bottom: 10px;"
      suffix-icon="el-icon-search"
        placeholder="输入关键字进行过滤"
        v-model="filterText">
      </el-input>
      <div class="treebox">
        <el-tree
        class="filter-tree"
        :data="data"
        show-checkbox
        :props="defaultProps"
        :filter-node-method="filterNode"
        @check="handleCheckChange"
        ref="roleTree">
       </el-tree>
      </div>
    </div>
    <div class="rightbodybox">
      <div class="righttop">
        <el-form ref="form" :model="form" >
          <el-form-item label="">
            <el-row >
              <el-col :span="8">
                <el-radio-group v-model="form.radio" @change="handleRadioChange">
                  <el-radio label="1">十五分钟负荷</el-radio>
                  <el-radio label="2">小时平均负荷</el-radio>
                  <el-radio label="3">日平均负荷</el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="6">
                <el-radio-group v-model="form.radio3" size="small" @change="changetime">
                  <el-radio-button label="1">今日</el-radio-button>
                  <el-radio-button label="2">昨日</el-radio-button>
                  <el-radio-button label="3">上周同期</el-radio-button>
                  <el-radio-button label="4">上月今日</el-radio-button>
                </el-radio-group>
              </el-col>
              <el-col :span="7">
                <el-date-picker
                  v-model="value1"
                  size="small"
                  type="daterange"
                  :picker-options="pickerOptions"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-col>
              <el-col :span="3">
                <!-- <el-button size="small" @click="chongzhi">重置</el-button> -->
                <el-button type="primary" size="small" @click="submit">查询</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div class="echanftab">
        <!-- 图表盒子 -->
        <div class="fuheechart" ref="fuheechart"></div>
         <!-- 表格盒子 -->
        <div class="tablebox">
          <template>
            <el-table
              :data="tableData"
              border
              :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
              v-loading="loading"
              height="calc(100% - 1px)"
              style="width: 100%">
              <template slot="empty">
                <el-empty description="暂无数据"></el-empty>
              </template>
              <el-table-column
              v-for="(item,index) in tableColumns"
              :key="index"
              :align="item.align"
                :prop="item.prop"
                :label="item.label"
                :width="item.width">
              </el-table-column>
            </el-table>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getchecktreeapi,geyfuhequxianapi,getfuheliebiaoapi} from '@/api/energy-consumption/GeneralSituation/HomePage'
import * as echarts from 'echarts';
export default {
  name: 'CallPoliceIndex',

  data() {
    return {
      data: [],
      loading:false,
      form: { radio3: '1', radio: '1', },
      value1: ['',''],
      tableData:[],
      filterText:'',
      defaultProps: {
        label: 'name',
        children:'childrenList'
      },
      tableColumns:[],
      treelist:[],
      selectDate: '', // 存储第一个选定日期的时间戳
      pickerOptions: {
        disabledDate: (time) => {
          if (this.selectDate !== '') {
            const oneDay = 24 * 3600 * 1000; // 一天的毫秒数
            const thirtyDays = 1 * oneDay; // 30天的毫秒数
            const minTime = this.selectDate - thirtyDays;
            const maxTime = this.selectDate + thirtyDays;
            let today = new Date();
            today.setHours(0, 0, 0, 0); // 设置为今天的0点
            // 限制可选日期：不可早于minTime，不可晚于maxTime和今天
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > today.getTime();
          }
        },
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate ? minDate.getTime() : '';
          if (maxDate) {
            this.selectDate = '';
          }
        },
      }
    };
  },
  async mounted() {
    const { data: { entity: { childrenList } } } = await getchecktreeapi()
    // this.data = this.addDisabledFlag(childrenList)
    this.data = childrenList
    this.gettime()
  },
  methods: {
    // 查询
    submit() {
      if(!this.treelist.length) return this.$message.warning('请先选择用电单位')
      // 将日期字符串转换为时间戳
      const date1 = new Date(this.value1[0]).getTime();
      const date2 = new Date(this.value1[1]).getTime();
      // 计算时间戳间隔的天数
      const diffDays = Math.abs((date2 - date1) / (1000 * 60 * 60 * 24));
      if((this.form.radio=='1'||this.form.radio=='2')&&diffDays>1) return this.$message.warning('分钟或小时平均负荷查询间隔天数不超过2天')
      const companyNos = this.treelist.map(ele => ele.companyNo).join(',');
      this.getfuheech(companyNos)
      this.gettablelist()
    },
    // 重置
    chongzhi(){
      this.form={ radio3: '1', radio: '1', },
      this.gettime()
      this.submit()
    },
    handleRadioChange(val) {
      // 根据选择的值动态设置可选择时间范围
      if (val === '1' || val === '2') {
        this.pickerOptions.disabledDate = (time) => {
          if (this.selectDate !== '') {
            const oneDay = 24 * 3600 * 1000; // 一天的毫秒数
            const thirtyDays = 1 * oneDay; // 30天的毫秒数
            const minTime = this.selectDate - thirtyDays;
            const maxTime = this.selectDate + thirtyDays;
            let today = new Date();
            today.setHours(0, 0, 0, 0); // 设置为今天的0点
            // 限制可选日期：不可早于minTime，不可晚于maxTime和今天
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > today.getTime();
          }
        };
        this.pickerOptions.onPick = ({ maxDate, minDate }) => {
          this.selectDate = minDate ? minDate.getTime() : '';
          if (maxDate) {
            this.selectDate = '';
          }
        }
      } else {
        this.pickerOptions.disabledDate = (time) => {
          return false;
        };
      }
    },
    // 树节点选择
    handleCheckChange(data, obj) {
      this.treelist = obj.checkedNodes
      console.log(this.treelist);
      this.submit()
    },
    // 编写递归 禁用companyNo为null的节点
    addDisabledFlag(list) {
      list.forEach(ele => {
        if (!ele.companyNo) {
          ele['disabled']=true
        }
        if (ele.childrenList&& ele.childrenList.length) {
          this.addDisabledFlag(ele.childrenList)
        }
      })
      return list
    },
    // 时间单选
    changetime(val) {
      if (val == '1') {
        this.gettime()
      } else if (val == '2') {
        // 获取昨日
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        const yesterdayFormatted = yesterday.toISOString().split('T')[0];
        this.value1=[yesterdayFormatted,yesterdayFormatted]
      } else if (val == '3') {
        // 获取上周同期日期
        const lastWeek = new Date();
        lastWeek.setDate(lastWeek.getDate() - 7);
        const lastWeekFormatted = lastWeek.toISOString().split('T')[0];
        this.value1=[lastWeekFormatted,lastWeekFormatted]
      } else if (val == '4') {
        // 获取上月同期日期
        const lastMonth = new Date();
        lastMonth.setMonth(lastMonth.getMonth() - 1);
        const lastMonthFormatted = lastMonth.toISOString().split('T')[0];
        this.value1=[lastMonthFormatted,lastMonthFormatted]
      }
    },
    // 获取表格数据
    async gettablelist() {
      this.loading = true
      const companyNos = []
      this.tableColumns = []
      this.tableData=[]
      this.treelist.map(ele => companyNos.push(ele.companyNo+'_'+ele.name))
      const res = await getfuheliebiaoapi({
        companyNameNos:companyNos.join(','), dateType: this.form.radio, startTime: this.value1[0], endTime: this.value1[1]
      })
      const list = res.data.list
      // 构建表头数据
      this.tableColumns = [
        {
          prop: "timeReading",
          label: "日期",
          width: "200",
          align: "center",
        }
      ];
      list.forEach((item, index) => {
        this.tableColumns.push({
          prop: `name${index + 1}`,
          label: item.name,
          align:'right'
        });
      });
      // 获取表格数据
      if (list[0]) {
        list[0].datalist.forEach((data, index) => {
          const rowData = {
            timeReading: data.timeReading
          };
          list.forEach((item, i) => {
            rowData[`name${i + 1}`] = item.datalist[index].valueReading;
          });
          this.tableData.push(rowData);
       })
      } else {
        this.tableColumns = []
        this.tableData=[]
      }
      this.loading=false
    },
    // 获取负荷图表
    async getfuheech(companyNos) {
      var chartDom = this.$refs.fuheechart
      var myChart = echarts.init(chartDom);
      const { data: { list } } = await geyfuhequxianapi({
        companyNos, dateType: this.form.radio, startTime: this.value1[0], endTime: this.value1[1]
      })
      const colorlist=['#2796fe','#f3da59']
      const timePoints=list[0]?.datalist.map(ele=>ele.timeReading)
      const series= list.map((ele,index) => {
        return {
            name:ele.name,
            type: 'line',
            smooth: true,
              showSymbol: false,
              symbol: 'none',
              lineStyle: {
                  color: colorlist[index] // 设置线条颜色为红色
              },
              itemStyle: {
                  color: colorlist[index] // 设置图例颜色为红色
              },
              data: ele.datalist.map(ele=>ele.valueReading),
          }

      })
      var option;
      option = {
        grid: {
          left: '3%',
          right: '1%',
          bottom: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: timePoints
        },
        legend: {},
        tooltip: {
          trigger: 'axis'
        },
        yAxis: {
          type: 'value'
        },
        series: series
      };
      myChart.clear();
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month=mon<10?'0'+mon:mon
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      this.value1=[year+'-'+month+'-'+day,year+'-'+month+'-'+day]
    },
    // 树节点过滤
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      }
    },
  watch: {
      filterText(val) {
        this.$refs.roleTree.filter(val);
      }
    },

};
</script>

<style scoped>
.supperbox{
  height: 100%;
  padding: 10px;
  display: flex;
  .lefttree{
    width: 300px;
    background-color: #fff;
    padding: 20px;
    height: 100%;
    margin-right: 10px;
    .treebox{
      height: 95%;
      overflow: auto;
    }
  }
  .rightbodybox{
    width: calc(100% - 310px);
    .righttop{
      height: 80px;
      margin-bottom: 10px;
      background-color: #fff;
      padding: 20px;
    }
    .echanftab{
      background-color: #fff;
      padding: 20px;
      height: calc(100% - 90px);
      .tablebox, .fuheechart{
        height: 50%;
      }
    }
  }
}
::v-deep .el-col-3{
  text-align: right;
}
::v-deep .el-radio{
  margin-right:10px;
}
</style>